package jehc.cloud.log.client.filter;

import jehc.cloud.common.util.StringUtil;
import jehc.cloud.log.client.annotation.OperationLogAnnotation;
import jehc.cloud.log.client.request.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Desc 重写参数过滤器
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@WebFilter(filterName = "httpFilter", urlPatterns = {"/*"})
@Order(-1)
@Slf4j
public class HttpFilter implements Filter {

    private List<HandlerMapping> handlerMappings;

    /**
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     *
     * @param applicationContext
     */
    public HttpFilter(ApplicationContext applicationContext) {
        Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
                HandlerMapping.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<>(matchingBeans.values());
            AnnotationAwareOrderComparator.sort(this.handlerMappings);
        }
    }

    /**
     *
     * @param request
     * @param response
     * @param chain
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            HandlerExecutionChain handlerExecutionChain = getHandler(httpServletRequest);
            Object handler = handlerExecutionChain != null ? handlerExecutionChain.getHandler() : null;

            Boolean needOperationLog = false;
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                needOperationLog = handlerMethod.hasMethodAnnotation(OperationLogAnnotation.class);//需要解密
            }
            if(needOperationLog){
                ServletRequest requestWrapper = null;
                String contentType = request.getContentType();
                if (request instanceof HttpServletRequest) {
                    if (!StringUtil.isEmpty(contentType)) {
                        if(!contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)){//过滤附件
                            requestWrapper = new RequestWrapper((HttpServletRequest) request);
                        }
                    }
                }
                if (requestWrapper == null) {
                    chain.doFilter(request, response);
                } else {
                    chain.doFilter(requestWrapper, response);
                }
            }else{
                chain.doFilter(request, response);
                return;
            }

        } catch (IOException e) {
            log.error("HttpFilter io error.{}",e);
        } catch (ServletException e) {
            log.error("HttpFilter ServletException error.{}",e);
        }catch (Exception e){
            log.error("HttpFilter exception error.{}",e);
        }
    }

    /**
     *
     */
    @Override
    public void destroy() {
    }

    /**
     *
     * @param request
     * @return
     * @throws Exception
     */
    private HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        if (this.handlerMappings != null) {
            for (HandlerMapping handlerMapping : this.handlerMappings) {
                HandlerExecutionChain handler = handlerMapping.getHandler(request);
                if (handler != null) {
                    return handler;
                }
            }
        }
        return null;
    }

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 参数注册器
     * @return
     */
    @Bean
    public FilterRegistrationBean signFilterRegistration() {
        FilterRegistrationBean<HttpFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new HttpFilter(applicationContext));
        registration.addUrlPatterns("/*");
        registration.setName("httpFilter");
        registration.setOrder(2);
        return registration;
    }
}
